import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios';


// 创建一个store   公共数据
export const useCartStore = defineStore('cart', () => {
    const goodsList = ref ([])
    const cartList = ref([])
    const getGoodsList = async () => {
        const res = await axios.get('/api/list');
        goodsList.value = res.data.data
    } 


    // 点击加号按钮
    const changeCount = (id,n = 1) => {
        const item = goodsList.value.find(v => v.id === id)
        const cartIndex = cartList.value.findIndex(v => v.id === id)
        if(cartIndex > -1) {
            cartList.value[cartIndex].count+=n
            if(cartList.value[cartIndex].count === 0) {
                cartList.value.splice(cartIndex,1)
            }
        }else {
            cartList.value.push({
                ...item,
                count:1
            })
        }

    }
    console.log(cartList)

    const total = computed (() => {
        return cartList.value.reduce((prev,next) => {
            return {
                count: prev.count + next.count,
                price:prev.price + next.count * next.price
            }
        },{ 
            count:0,
            price:0
        })
    })
    



  // 函数的返回值
  return {
    goodsList,
    cartList,
    getGoodsList,
    changeCount,
    total
   }
})
